import Vue from 'vue'
import { ACCESS_TOKEN } from "@/store/mutation-types"
import store from '@/store'

/**
 * 单点登录
 */
const init = (callback) => {
  console.log("-------单点登录开始-------");

  let st = getUrlParam("token");
  if(st){
    Vue.ls.set(ACCESS_TOKEN, st, 7 * 24 * 60 * 60 * 1000)
    validateSt(st,callback);
  }
  console.log("-------单点登录结束-------");
};
const SSO = {
  init: init
};
function getUrlParam(paraName) {
  var url = document.location.toString();
  var arrObj = url.split("?");

  if (arrObj.length > 1) {
    var arrPara = arrObj[1].split("&");
    var arr;
    for (var i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split("=");
      if (arr != null && arr[0] === paraName) {
        let str=arr[1]
        let token=''
        if(str.indexOf('#/')>-1){
          token=arr[1].split('#/')[0]
        }else
        {
          token =arr[1]
        }
        return token;
      }
    }
    return "";
  }
  else {
    return "";
  }
}

function validateSt(token,callback){
  let params = {
    token: token,
  };
  store.dispatch('SSOLogin',params).then(res => {
    if(res.success){
      window.location.href =  window.location.origin
      loginSuccess(callback);
    }else{
      console.log('验证失败')
      alert(res.message)
      window.location.href =window._CONFIG['baseUrl']+'/#/user/login'
    }
  }).catch((err) => {
    console.log(err)
    // notification 弹窗弹不出来 loading页面zindex层级太高 遮住了 用alert提示之后跳转到登录页
    alert(err.message)
    window.location.href =window._CONFIG['baseUrl']+'/#/user/login'

  });
}

function loginSuccess (callback) {
  callback();
}
export default SSO;